import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../../base/imageres.dart';
import '../../base/constant.dart';
import '../../base/eventbus.dart';
import '../../base/log.dart';
import '../../base/stringres.dart';
import '../../base/theme.dart';
import '../../database/app_data.dart';
import '../../util/toast_util.dart';
import '../../views/jsw_base_view.dart';

///女性健康下面的记录生理周期页面
class RecordMenstrualPage extends StatefulWidget {
  final String userId;
  final String recordTitle;
  final String recordDay;
  final String recordDayTitle;
  final bool isMenstrualRecord;
  final Map<String, dynamic> recordMap;

  const RecordMenstrualPage(
      {super.key,
        required this.userId,
        required this.recordTitle,
        required this.recordDay,
        required this.recordDayTitle,
        required this.isMenstrualRecord,
        required this.recordMap});

  @override
  State<StatefulWidget> createState() {
    return _RecordMenstrualPageState();
  }
}

class RecordController extends GetxController {
  int _flowIndex = -1;

  void updateFlowIndex(int index) {
    _flowIndex = index;
    update();
  }

  int _colorIndex = -1;

  void updateColorIndex(int index) {
    _colorIndex = index;
    update();
  }

  int _dysmenorrheaIndex = -1;

  void updateDysmenorrheaIndex(int index) {
    _dysmenorrheaIndex = index;
    update();
  }

  List<int> _symptomSelected = List.filled(8, 0);

  void updateSymptomSelected(int index) {
    _symptomSelected[index] = _symptomSelected[index] == 1 ? 0 : 1;
    update();
  }

  int _leucorrheaIndex = -1;

  void updateLeucorrheaIndex(int index) {
    _leucorrheaIndex = index;
    update();
  }

  int _moodIndex = -1;

  void updateMoodIndex(int index) {
    _moodIndex = index;
    update();
  }

  int _ovulationIndex = -1;

  void updateOvulationIndex(int index) {
    _ovulationIndex = index;
    update();
  }

  int _sexIndex = -1;

  void updateSexIndex(int index) {
    _sexIndex = index;
    update();
  }
}

class _RecordMenstrualPageState extends State<RecordMenstrualPage> {
  static const _tag = '[page_record_menstrual.dart][_RecordMenstrualPageState]';

  ///记录生理周期的控制器
  final controller = Get.put(RecordController());

  ///备注信息控制器
  final TextEditingController _notesController =
  TextEditingController(text: '');

  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    controller._flowIndex = widget.recordMap["flowIndex"];
    controller._colorIndex = widget.recordMap["colorIndex"];
    controller._dysmenorrheaIndex = widget.recordMap["dysmenorrheaIndex"];
    controller._symptomSelected = widget.recordMap["symptomSelected"];
    controller._leucorrheaIndex = widget.recordMap["leucorrheaIndex"];
    controller._moodIndex = widget.recordMap["moodIndex"];
    controller._ovulationIndex = widget.recordMap["ovulationIndex"];
    controller._sexIndex = widget.recordMap["sexIndex"];
    _notesController.text = widget.recordMap["notes"];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: true,
        body: Stack(
          children: [
            Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(ImageRes.bg_health_main),
                  fit: BoxFit.cover, // 图片填充方式
                ),
              ),
            ),
            SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  //顶部标题
                  AppBar(
                    elevation: 0.0,
                    backgroundColor: Colors.transparent,
                    title: EasyTouch(
                      width: double.infinity,
                      padding: const EdgeInsets.only(right: 55),
                      child: Text(
                        widget.recordDayTitle,
                        textAlign: TextAlign.center,
                        style: ThemeUtil.toolbar,
                      ),
                    ),
                    leading: IconButton(
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      hoverColor: Colors.transparent,
                      icon: const Icon(
                        Icons.arrow_back,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        Get.back();
                      },
                    ),
                  ),

                  //小标题
                  Container(
                      width: double.infinity,
                      alignment: Alignment.center,
                      margin: const EdgeInsets.only(bottom: 10),
                      child: Text(
                        widget.recordTitle,
                        style: ThemeUtil.p2.copyWith(
                            fontSize: 14,
                            color: const Color(ThemeUtil.primaryWhiteValue50)),
                      )),

                  //流量选择
                  widget.isMenstrualRecord
                      ? GetBuilder<RecordController>(
                      builder: (_) => _buildCategory(
                        title: StringRes.flow,
                        items: [
                          StringRes.very_light,
                          StringRes.light,
                          StringRes.medium,
                          StringRes.heavy,
                          StringRes.very_heavy
                        ],
                        iconPaths: ImagePathData.selectedFlowPaths,
                        selectedIndex: controller._flowIndex,
                        onSelect: (index) {
                          controller.updateFlowIndex(index);
                          DartLog.i(_tag,
                              '流量选择 _flowIndex：${controller._flowIndex}}');
                        },
                      ))
                      : Container(),

                  // 颜色
                  widget.isMenstrualRecord
                      ? GetBuilder<RecordController>(
                      builder: (_) => _buildCategory(
                        title: StringRes.color,
                        items: [
                          StringRes.light_red,
                          StringRes.bright_red,
                          StringRes.dark_red,
                          StringRes.brown,
                          StringRes.black
                        ],
                        iconPaths: ImagePathData.selectedColorPaths,
                        selectedIndex: controller._colorIndex,
                        onSelect: (index) {
                          controller.updateColorIndex(index);
                          DartLog.i(_tag,
                              '颜色选择 _colorIndex：$controller._colorIndex}');
                        },
                      ))
                      : Container(),

                  // 痛经
                  widget.isMenstrualRecord
                      ? GetBuilder<RecordController>(
                      builder: (_) => _buildCategory(
                        title: StringRes.dysmenorrhea,
                        items: [
                          StringRes.no_pain,
                          StringRes.mild,
                          StringRes.noticeable,
                          StringRes.severe,
                          StringRes.extreme
                        ],
                        iconPaths: ImagePathData.selectedDysmenorrheaPaths,
                        selectedIndex: controller._dysmenorrheaIndex,
                        onSelect: (index) {
                          controller.updateDysmenorrheaIndex(index);
                          DartLog.i(_tag,
                              '痛经选择 _dysmenorrheaIndex：${controller._dysmenorrheaIndex}}');
                        },
                      ))
                      : Container(),

                  // 症状（可多选）
                  GetBuilder<RecordController>(
                      builder: (_) => _buildMultiSelectCategory(
                        title: StringRes.symptoms_multiple_choices,
                        items: [
                          StringRes.abdominal_pain,
                          StringRes.headache,
                          StringRes.breast_tenderness,
                          StringRes.body_ches,
                          StringRes.low_back_pain,
                          StringRes.diarrhea,
                          StringRes.constipation,
                          StringRes.back_pain
                        ],
                        iconPaths: ImagePathData.selectedSymptomPaths,
                        selectedList: controller._symptomSelected,
                        onSelect: (index) {
                          controller.updateSymptomSelected(index);
                          DartLog.i(_tag,
                              '症状（可多选） _symptomSelected：${controller._symptomSelected.toString()}}');
                        },
                      )),

                  // 白带
                  GetBuilder<RecordController>(
                    builder: (_) => _buildCategory(
                      title: StringRes.leucorrhea,
                      items: [
                        StringRes.sticky,
                        StringRes.paste_like,
                        StringRes.watery,
                        StringRes.egg_white_like
                      ],
                      iconPaths: ImagePathData.selectedLeucorrheaPaths,
                      selectedIndex: controller._leucorrheaIndex,
                      onSelect: (index) {
                        controller.updateLeucorrheaIndex(index);
                        DartLog.i(_tag,
                            '白带 _leucorrheaIndex：${controller._leucorrheaIndex}}');
                      },
                    ),
                  ),

                  // 心情
                  GetBuilder<RecordController>(
                      builder: (_) => _buildCategory(
                        title: StringRes.mood,
                        items: [
                          StringRes.happy,
                          StringRes.calm,
                          StringRes.tired,
                          StringRes.anxious,
                          StringRes.depressed
                        ],
                        iconPaths: ImagePathData.selectedMoodPaths,
                        selectedIndex: controller._moodIndex,
                        onSelect: (index) {
                          controller.updateMoodIndex(index);
                          DartLog.i(_tag,
                              '心情 _moodIndex：${controller._moodIndex}}');
                        },
                      )),

                  // 排卵
                  GetBuilder<RecordController>(
                      builder: (_) => _buildCategory(
                        title: StringRes.ovulation,
                        items: [
                          StringRes.not_ovulated,
                          StringRes.ovulated,
                        ],
                        iconPaths: ImagePathData.selectedOvulationPaths,
                        selectedIndex: controller._ovulationIndex,
                        onSelect: (index) {
                          controller.updateOvulationIndex(index);
                          DartLog.i(_tag,
                              '排卵 _ovulationIndex：${controller._ovulationIndex}}');
                        },
                      )),

                  // 爱爱
                  GetBuilder<RecordController>(
                      builder: (_) => _buildCategory(
                        title: StringRes.sex,
                        items: [
                          StringRes.have,
                          StringRes.not_have,
                        ],
                        iconPaths: ImagePathData.selectedSexPaths,
                        selectedIndex: controller._sexIndex,
                        onSelect: (index) {
                          controller.updateSexIndex(index);
                          DartLog.i(_tag,
                              '爱爱 _sexIndex：${controller._sexIndex}}');
                        },
                      )),

                  Container(
                      width: double.infinity,
                      margin: const EdgeInsets.only(
                          top: 25, left: 15, right: 15, bottom: 20),
                      padding: const EdgeInsets.only(
                          top: 15, bottom: 15, left: 15, right: 15),
                      decoration: BoxDecoration(
                          color: const Color(0XFF1B1D20),
                          borderRadius: BorderRadius.circular(20.0)),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 备注
                          Text(
                            StringRes.notes,
                            style: ThemeUtil.mp2,
                          ),
                          const SizedBox(
                            height: 10,
                          ),
                          TextField(
                            cursorColor:
                            const Color(ThemeUtil.primarProgressValue),
                            controller: _notesController,
                            style: ThemeUtil.mp2.copyWith(fontSize: 13),
                            decoration: const InputDecoration(
                              fillColor: Colors.black,
                              filled: true,
                              border: OutlineInputBorder(
                                borderSide:
                                BorderSide(color: Colors.transparent),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderSide:
                                BorderSide(color: Colors.transparent),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderSide:
                                BorderSide(color: Colors.transparent),
                              ),
                            ),
                            maxLines: 6,
                            maxLength: 120,
                            textInputAction: TextInputAction.done,
                            onSubmitted: (value) {
                              FocusScope.of(context).unfocus();
                            },
                          ),
                        ],
                      )),

                  Container(
                    margin: EdgeInsets.only(bottom: 50 + MediaQuery.of(context).viewPadding.bottom, left: 15, right: 15),
                    height: 50,
                    alignment: Alignment.center,
                    decoration: ThemeUtil.themeConStyle,
                    child: TextButton(
                      style: ThemeUtil.themebtnStyle,
                      onPressed: () async {
                        String inputText = _notesController.text;
                        if (inputText.isEmpty) {
                          ToastUtil.show(StringRes.notes_is_null_tips);
                          return;
                        }
                        DartLog.i(_tag, '备注的信息：$inputText');
                        Map<String, dynamic> dataMap = <String, dynamic>{};
                        dataMap['flowIndex'] = controller._flowIndex;
                        dataMap['colorIndex'] = controller._colorIndex;
                        dataMap['dysmenorrheaIndex'] =
                            controller._dysmenorrheaIndex;
                        dataMap['symptomSelected'] =
                            controller._symptomSelected;
                        dataMap['leucorrheaIndex'] =
                            controller._leucorrheaIndex;
                        dataMap['moodIndex'] = controller._moodIndex;
                        dataMap['ovulationIndex'] = controller._ovulationIndex;
                        dataMap['sexIndex'] = controller._sexIndex;
                        dataMap['notes'] = inputText;
                        DartLog.i(_tag, 'dataMap：${dataMap.toString()}');
                        showLoadingDialog();
                        APPDatabase.saveHealthRecordData(
                            widget.userId,
                            widget.recordDay,
                            controller._flowIndex,
                            controller._colorIndex,
                            controller._dysmenorrheaIndex,
                            controller._symptomSelected,
                            controller._leucorrheaIndex,
                            controller._moodIndex,
                            controller._ovulationIndex,
                            controller._sexIndex,
                            inputText)
                            .then((value) {
                          hideLoadingDialog();
                          if (value) {
                            //同步女性健康服务器成功
                            EventBusUtil.getInstance().fire(DataEvent(
                                HealthDataType.REFRESH_MENSTRUAL_RECORD_DATA,
                                dataMap));
                            Get.back();
                          }
                        });
                      },
                      child: Text(StringRes.save,
                          textAlign: TextAlign.center, style: ThemeUtil.p2),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ));
  }

  /// 构建单选分类（如流量、颜色等）
  Widget _buildCategory({
    required String title,
    required List<String> items,
    required List<String> iconPaths,
    required int selectedIndex,
    required Function(int) onSelect,
  }) {
    DartLog.i(_tag, '_buildCategory 重新刷新 title：$title');
    final screenWidth = MediaQuery.of(context).size.width;
    final eachPartWidth = (screenWidth - 30) / 4;
    return Container(
        margin: const EdgeInsets.only(top: 10, left: 15, right: 15),
        padding: const EdgeInsets.only(top: 20,bottom: 30),
        decoration: BoxDecoration(
          gradient: const LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0XFF1B1D20),
              Color(0XFF141518)
            ],
          ),
          borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(left: 15),
                  child: Text(
                    title,
                    textAlign: TextAlign.center,
                    style: ThemeUtil.mp2,
                  ),
                ),
              ],
            ),
            Wrap(
              children: List.generate(items.length, (index) {
                return GestureDetector(
                    onTap: () => onSelect(index),
                    child: Column(
                      children: <Widget>[
                        Container(
                          width: eachPartWidth,
                          alignment: Alignment.center,
                          margin: const EdgeInsets.only(top: 10, bottom: 10),
                          decoration: BoxDecoration(
                            shape: BoxShape.circle, // 圆形形状
                            border: Border.all(
                              color: selectedIndex == index ? Colors.white : Colors.transparent,
                              width: 1.5, // 边框宽度
                            ),
                          ),
                          child: Image(
                            image: AssetImage(iconPaths[index]),
                            width: 48,
                            height: 48,
                          ),
                        ),
                        Container(
                          width: eachPartWidth,
                          alignment: Alignment.center,
                          child: Text(
                            items[index],
                            textAlign: TextAlign.center,
                            style: ThemeUtil.mp2.copyWith(fontSize: 13),
                          ),
                        ),
                      ],
                    ));
              }),
            ),
          ],
        ));
  }

  /// 构建多选分类（如症状）
  Widget _buildMultiSelectCategory({
    required String title,
    required List<String> items,
    required List<String> iconPaths,
    required List<int> selectedList,
    required Function(int) onSelect,
  }) {
    final screenWidth = MediaQuery.of(context).size.width;
    final eachPartWidth = (screenWidth - 30) / 4;
    return Container(
        margin: const EdgeInsets.only(top: 10, left: 15, right: 15),
        padding: const EdgeInsets.only(top: 20,bottom: 30),
        decoration: BoxDecoration(
          gradient: const LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0XFF1B1D20),
              Color(0XFF141518)
            ],
          ),
          borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(left: 15),
                  child: Text(
                    title,
                    textAlign: TextAlign.center,
                    style: ThemeUtil.mp2,
                  ),
                ),
              ],
            ),
            Wrap(
              children: List.generate(items.length, (index) {
                return GestureDetector(
                  onTap: () {
                    onSelect(index);
                  },
                  child: Column(
                    children: [
                      Container(
                        width: eachPartWidth,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle, // 圆形形状
                          border: Border.all(
                            color: selectedList[index] == 1 ? Colors.white : Colors.transparent,
                            width: 1.5, // 边框宽度
                          ),
                        ),
                        margin: const EdgeInsets.only(top: 10, bottom: 10),
                        child: Image(
                          image: AssetImage(iconPaths[index]),
                          width: 48,
                          height: 48,
                        ),
                      ),
                      Container(
                        width: eachPartWidth,
                        alignment: Alignment.center,
                        child: Text(
                          items[index],
                          textAlign: TextAlign.center,
                          style: ThemeUtil.mp2.copyWith(fontSize: 13),
                        ),
                      ),
                    ],
                  ),
                );
              }),
            ),
          ],
        ));
  }

  /// 显示加载等待框
  BuildContext? _dialogContext;

  void showLoadingDialog() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          _dialogContext = context;
          return const Center(
            child: CircularProgressIndicator(
              color: Color(ThemeUtil.primarProgressValue),
            ),
          );
        },
      );
    });
  }

  /// 隐藏加载等待框
  void hideLoadingDialog() {
    if (_dialogContext != null && Navigator.canPop(_dialogContext!)) {
      Navigator.pop(_dialogContext!);
      _dialogContext = null;
    }
  }
}
